package com.pervasive.geo_tag.servlets;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/DeleteServlet")
public class DeleteServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String SERVER_REPO = "C:\\Users\\mediaworld\\workspaceReti\\GeoTagWebService\\WebContent\\";

   
    public DeleteServlet() {
        super();
    }


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
		 String dbName = "android_geo_tag";
		 Statement stmt = null;
		 ResultSet rs = null;
		 String fileName = null;
		 String uriPhoto = null;
		 String query;
		 String queryDelete;
		 Connection con = null;
		 int id_photo;
		 
		 try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
		} catch (InstantiationException e) {e.printStackTrace();
		} catch (IllegalAccessException e) {e.printStackTrace();
		} catch (ClassNotFoundException e) {e.printStackTrace();}
		
		 try {
			con = DriverManager.getConnection("jdbc:mysql://localhost:3306/android_geo_tag", "root", "seppiessa");
		} catch (SQLException e) {e.printStackTrace();}
		 
		 try {
			stmt = con.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
		} catch (SQLException e) {e.printStackTrace();}
		 
		 id_photo = Integer.parseInt(request.getParameter("id_photo"));
		 
		 query = "select * from " + dbName + ".photo where id_photo = " + id_photo ;
		 try {
			rs = stmt.executeQuery(query);
		} catch (SQLException e) {e.printStackTrace();}
		 
		 try {
			if(rs.next()){
				uriPhoto = rs.getString("URI");
				fileName = uriPhoto.substring(42, uriPhoto.length());
				File f = new File(SERVER_REPO + fileName);
				 if(!f.delete())
					 System.err.println("Failure: the selected file cannot be delete");
			 }
		} catch (SQLException e) {e.printStackTrace();}
		
		queryDelete = "delete from " +dbName +".photo where id_photo = " + id_photo;
		
		try {
			stmt.executeUpdate(queryDelete);
		} catch (SQLException e) {e.printStackTrace();}
	
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}

}
